package com.mcp.util;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * JSON处理工具类
 */
public class JsonUtils {
    private static final ObjectMapper mapper = new ObjectMapper();

    static {
        // 确保JSON处理使用UTF-8
        mapper.configure(JsonParser.Feature.ALLOW_COMMENTS, false);
        mapper.configure(JsonParser.Feature.AUTO_CLOSE_SOURCE, true);
    }

    public static String toJson(Object obj) {
        try {
            return mapper.writeValueAsString(obj);
        } catch (JsonProcessingException e) {
            throw new RuntimeException("JSON序列化失败", e);
        }
    }

    public static <T> T fromJson(String json, Class<T> clazz) {
        try {
            return mapper.readValue(json, clazz);
        } catch (JsonProcessingException e) {
            // 添加原始JSON信息便于调试
            throw new RuntimeException("JSON反序列化失败，原始内容: " + json, e);
        }
    }
}